package com.icloud.cer.rest.msg.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.msg.AbsMsgObject;
import com.icloud.cer.rest.msg.MessageHeader;
import com.icloud.cer.rest.msg.MessageHolder;
import com.icloud.cer.rest.util.LogUtils;

public class ObjectEncoder extends ProtocolEncoderAdapter{
	
	private static final Logger log = LoggerFactory.getLogger(ObjectEncoder.class);

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		if (!(message instanceof MessageHolder)) {
			throw new RuntimeException("Error mina message, or mina handler config error.");
		}
		MessageHolder holder = (MessageHolder)message;
		if(!checkHolder(holder)) {
			log.error("holder is invalid.");
			return;
		}
		
		short command = holder.getCommand();
		LogUtils.printMessage(log, command, session);
		
		MessageHeader head = holder.getHead();
		byte[] headData = head.serialize();
		IoBuffer buf = IoBuffer.allocate(headData.length + head.getSize_());
		buf.setAutoExpand(true);
		buf.put(headData);
		
		AbsMsgObject body = holder.getValue();
		byte[] bodyData = body.serialize();
		buf.put(bodyData);
		buf.flip();
		out.write(buf);
		log.info("encode buffer:" + buf);
		
	}
	
	private boolean checkHolder(MessageHolder holder) {
		if (holder.getCommand() == 0) {
			log.error("command is 0");
			return false;
		}
		return true;
	}

}
